package action;

import java.util.List;

import com.opensymphony.xwork2.ModelDriven;

import entity.Users;
import service.UsersDAO;
import service.impl.UsersDAOImpl;

public class UsersAction extends SuperAction implements ModelDriven<Users> {

	private static final long serialVersionUID = 4317500994450323565L;
	private Users user = new Users();
	
	public String login()
	{
		UsersDAO udao = new UsersDAOImpl();
		List<Users> list = udao.usersLogin(user);
		
		if (list != null && list.size() > 0) {
			session.setAttribute("loginUserName", list.get(0).getUsername());
			session.setAttribute("loginUserUid", list.get(0).getUid());
			session.setAttribute("loginUserAuth", list.get(0).getAuth());
			this.persistUser();
			
			return "login_success";
		} else {
			return "login_failed";
		}
	}
	
	//保存所有用户名到session
	public void persistUser()
	{
		UsersDAO udao = new UsersDAOImpl();
		List<Users> list = udao.getUsers();
		
		session.setAttribute("allUsers", list);
	}
	
	public String logout()
	{
	    session.invalidate();//清空session信息

		return "logout_success";
	}
	
	@Override
	public Users getModel() {
		// TODO Auto-generated method stub
		return this.user;
	}
	
	public String modifyPassword()
	{
		return "modify_password";
	}
	
	public String admin()
	{
		if (session.getAttribute("loginUserAuth") != null && session.getAttribute("loginUserAuth") != "") {
			if (Integer.parseInt(session.getAttribute("loginUserAuth").toString()) != 1) {
				return "logout_success";//无权限
			}
		} else {
			return "logout_success";//无权限
		}
		
		return "admin";
	}
	
	public String addUser()
	{
		UsersDAO udao = new UsersDAOImpl();
		
		String username = "";
		String password = "";
		int auth = 0;
		
		if (request.getParameter("username") != "" && request.getParameter("username") != null) {
			username = request.getParameter("username");
		}
		if (request.getParameter("password") != "" && request.getParameter("password") != null) {
			password = request.getParameter("password");
		}
		if (request.getParameter("auth") != "" && request.getParameter("auth") != null) {
			auth = Integer.parseInt(request.getParameter("auth"));
		}
		
		if (udao.addUser(username, password, auth)) {
			session.setAttribute("addUser", 1);
			//重新保存所有用户信息
			List<Users> list = udao.getUsers();
			
			session.setAttribute("allUsers", list);
		} else {
			session.setAttribute("addUser", 2);
		}
		
		return "admin";
	}

}
